package com.ruoyi.ucar.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.obs.services.model.AccessControlList;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ucar.boreq.*;
import com.ruoyi.ucar.boresp.*;
import com.ruoyi.ucar.common.CommonCheXinMengBoResp;
import com.ruoyi.ucar.common.ResultEnum;
import com.ruoyi.ucar.constants.UcarConstants;
import com.ruoyi.ucar.domain.po.*;
import com.ruoyi.ucar.moreq.*;
import com.ruoyi.ucar.util.PuppeteerScreenshotUtil;
import com.ruoyi.ucar.voreq.OrderGetReturnMoneyVoReq;
import com.ruoyi.ucar.voreq.TotalCountVoReq;
import com.ruoyi.ucar.voresp.OrderTotalCountDataVo;
import com.ruoyi.ucar.voresp.OrderTotalCountDataVoResq;
import com.ruoyi.ucar.voresp.ProductTotalCountDataVo;
import com.ruoyi.ucar.voresp.ProductTotalCountDataVoResq;

import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ucar.common.CommonLemonBoResp;
import com.ruoyi.ucar.domain.*;
import com.ruoyi.ucar.mapper.*;
import com.ruoyi.ucar.service.ISysFileMainService;
import com.ruoyi.ucar.service.ITOrderService;
import com.ruoyi.ucar.service.UCarQueryApiService;
import com.ruoyi.ucar.util.CommonUtil;
import com.ruoyi.ucar.util.NanoTimestampUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单主Service业务层处理
 * 
 * @author sungangbin
 * @date 2025-05-13
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService
{
    @Autowired
    private TOrderMapper tOrderMapper;

    @Autowired
    private TOrderProductDataMapper tOrderProductDataMapper;

    @Autowired
    private TProductMapper tProductMapper;

    @Autowired
    private TCustomerMapper tCustomerMapper;

    @Autowired
    private UCarQueryApiService  uCarQueryApiService;

    @Autowired
    private SysFileDataMapper sysFileDataMapper;

    @Autowired
    private ISysFileMainService sysFileMainService;

    @Value("${file.localSavePath}")
    private String fileLocalSavePath;

    @Autowired
    private   TConsumeDataMapper tConsumeDataMapper;

    @Value("${ucar.agencyFee}")
    private Double agencyFee;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public int reportUnReadMinusOne(ReportUnReadMinusOneBoReq reportUnReadMinusOneBoReq){

        TOrder tOrder= this.tOrderMapper.selectOne(new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderUuid,reportUnReadMinusOneBoReq.getOrderUuid()).eq(TOrder::getDeleteFlag,1l));
        if(StringUtils.isNull(tOrder)){
            return 0;
        }else {
            if(StringUtils.isNotNull(tOrder.getUnreadFlag())&&tOrder.getUnreadFlag()==1) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("orderUuid", reportUnReadMinusOneBoReq.getOrderUuid());
                map.put("deleteFlag", 1);
                TCustomer tCustomer = tCustomerMapper.queryCustomerReportUnReadNumber(map);
                if (tCustomer.getReportUnreadNumber() > 0) {
                    tOrder.setUnreadFlag(0l);
                    this.tOrderMapper.updateById(tOrder);
                    return tCustomerMapper.customerReportUnReadNumberMinusone(map);
                } else {
                    return 0;
                }
            }else{
                return 0;
            }
        }
    }

    @Override
    public OrderTotalCountDataVoResq orderTotalCount(TotalCountVoReq totalCountVoReq) {
        TotalCountBoReq totalCountBoReq=CommonUtil.objToObj(totalCountVoReq,TotalCountBoReq.class);
        totalCountBoReq.setDeleteFlag(1l);
        OrderTotalCountDataVoResq orderTotalCountDataVoResq=new OrderTotalCountDataVoResq();
        List<OrderTotalCountDataBo> orderTotalCountDataBos=tOrderMapper.orderTotalCount(totalCountBoReq);
        List<OrderTotalCountDataVo> orderTotalCountDataVos=new ArrayList<>();
        orderTotalCountDataBos.forEach(orderTotalCountDataBo -> {
            OrderTotalCountDataVo orderTotalCountDataVo=CommonUtil.objToObj(orderTotalCountDataBo,OrderTotalCountDataVo.class);
            orderTotalCountDataVo.setTotalProfit(orderTotalCountDataBo.getTotolIncome().subtract(orderTotalCountDataBo.getTotolDisburse()).subtract(orderTotalCountDataBo.getTotalGiftMoney()).subtract(orderTotalCountDataBo.getTotalAgencyFee()));
            orderTotalCountDataVos.add(orderTotalCountDataVo);
        });
        orderTotalCountDataVoResq.setOrderTotalCountDataVos(orderTotalCountDataVos);
        return orderTotalCountDataVoResq;
    }

    @Override
    public ProductTotalCountDataVoResq productTotalCount(TotalCountVoReq totalCountVoReq) {
        TotalCountBoReq totalCountBoReq=CommonUtil.objToObj(totalCountVoReq,TotalCountBoReq.class);
        totalCountBoReq.setDeleteFlag(1l);
        ProductTotalCountDataVoResq productTotalCountDataVoResq=new ProductTotalCountDataVoResq();
        List<ProductTotalCountDataBo> productTotalCountDataBos=tOrderMapper.productTotalCount(totalCountBoReq);
        List<ProductTotalCountDataVo> productTotalCountDataVos=new ArrayList<>();
        productTotalCountDataBos.forEach(productTotalCountDataBo -> {
            ProductTotalCountDataVo productTotalCountDataVo=CommonUtil.objToObj(productTotalCountDataBo,ProductTotalCountDataVo.class);
            productTotalCountDataVo.setTotalProfit(productTotalCountDataBo.getTotolIncome().subtract(productTotalCountDataBo.getTotolDisburse()).subtract(productTotalCountDataBo.getTotalGiftMoney()).subtract(productTotalCountDataBo.getTotalAgencyFee()));
            productTotalCountDataVo.setProductTypeDict(DictUtils.getDictLabel("product_type",productTotalCountDataBo.getProductType()));
            productTotalCountDataVos.add(productTotalCountDataVo);
        });
        productTotalCountDataVoResq.setProductTotalCountDataVos(productTotalCountDataVos);
        return productTotalCountDataVoResq;
    }

    @Override
    public OrderQueryProxyListBoResp proxyQueryOrderByCond(OrderListProxyQueryBoReq orderListProxyQueryBoReq) {
        OrderListProxyQueryMoReq orderListProxyQueryMoReq=CommonUtil.objToObj(orderListProxyQueryBoReq,OrderListProxyQueryMoReq.class);
        orderListProxyQueryMoReq.setProxyCustomerUuid(tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>()
                .eq(TCustomer::getSysUserId,SecurityUtils.getLoginUser()
                        .getUserId()).eq(TCustomer::getDeleteFlag,1L)).getCustomerUuid());
        orderListProxyQueryMoReq.setDeleteFlag(1l);
        List<OrderQueryProxyListPo>  orderQueryProxyListPos= tOrderMapper.orderListProxyQuery(orderListProxyQueryMoReq);
        if(StringUtils.isNotNull(orderQueryProxyListPos)&&orderQueryProxyListPos.size()>0){
            OrderQueryProxyListBoResp orderQueryProxyListBoResp=new OrderQueryProxyListBoResp();
            List<OrderQueryProxyListBo> orderQueryProxyListBos=new ArrayList<>();
            orderQueryProxyListPos.forEach(orderQueryProxyListPo -> {
                OrderQueryProxyListBo orderQueryProxyListBo=CommonUtil.objToObj(orderQueryProxyListPo,OrderQueryProxyListBo.class);
                orderQueryProxyListBo.setOrderStatusDict(DictUtils.getDictLabel("order_status",String.valueOf(orderQueryProxyListPo.getOrderStatus())));
                orderQueryProxyListBos.add(orderQueryProxyListBo);
            });
            orderQueryProxyListBoResp.setOrderQueryProxyListBos(orderQueryProxyListBos);
            return orderQueryProxyListBoResp;
        }else {
            return null;
        }
    }

    @Override
    public CheXinMengUrlListBoResp cheXinMenUrlList(CheXinMengUrlListQueryBoReq cheXinMengUrlListQueryBoReq) {
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("orderUuid",cheXinMengUrlListQueryBoReq.getOrderUuid());
        map.put("deleteFlag", 1);
        List<OrderMobileQueryListPo>  orderMobileQueryListPos=tOrderMapper.mobileQueryOrderByCond(map);
        if(StringUtils.isNotNull(orderMobileQueryListPos)&&orderMobileQueryListPos.size()>0){
            CheXinMengUrlListBoResp cheXinMengUrlListBoResp=new CheXinMengUrlListBoResp();
            List<String> reportUrls=new ArrayList<>();

            orderMobileQueryListPos.forEach(orderMobileQueryListPo -> {
                if(StringUtils.isNotEmpty(orderMobileQueryListPo.getQueryreportOrderId())&&"cheXinMengQueryAccident".equals(orderMobileQueryListPo.getProductType())){
                    CheXinMengGetReportBoReq cheXinMengGetReportBoReq=new CheXinMengGetReportBoReq();
                    cheXinMengGetReportBoReq.setOrderId(orderMobileQueryListPo.getQueryreportOrderId());
                    CommonCheXinMengBoResp commonCheXinMengBoResp= uCarQueryApiService.cheXinMengGetReport(cheXinMengGetReportBoReq);
                    if(StringUtils.isNotNull(commonCheXinMengBoResp.getReturnObj())){
                        reportUrls.add(((CheXinMengGetReportBoResp)commonCheXinMengBoResp.getReturnObj()).getReportUrl());
                    }
                }
            });
            cheXinMengUrlListBoResp.setReportUrls(reportUrls);
            return cheXinMengUrlListBoResp;
        }

        return null;
    }

    private String reportToImage(String reportUrl,String queryReportOrderId,String type){
        FileInputStream fileInputStream=null;
        File file=null;
        try {
            String fileName=CommonUtil.createUuid()+".png";
            String filePath=fileLocalSavePath+fileName;
            PuppeteerScreenshotUtil.captureFullPage(
                    reportUrl,
                    filePath,"9500"
            );
            file=new File(filePath);
            fileInputStream=new FileInputStream(file);
            String fileURl = sysFileMainService.obsUploadFile(fileName,fileInputStream, AccessControlList.REST_CANNED_PUBLIC_READ);
            return fileURl;
         } catch (Exception e) {
            logger.error(type+":"+queryReportOrderId+":车辆报告转图片失败：{}",e.getMessage());
         }finally {
            if(StringUtils.isNotNull(fileInputStream))
            {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    logger.error(type+":"+queryReportOrderId+":车辆报告转图片失败：{}",e.getMessage());
                }
            }
//            if(StringUtils.isNotNull(file))
//            {
//                file.delete();
//            }
        }
        return null;
    }


    @Transactional
    @Override
    public List<UcarOrderQueryApiBoResq> orderUseUcarQueryApi(UcarOrderQueryApiBoReq ucarOrdeQueryApiBoReq,TOrder order) {
             HashMap<String,Object> map=new HashMap<String,Object>();
             map.put("orderUuid",ucarOrdeQueryApiBoReq.getOrderUuid());
             map.put("deleteFlag", 1);
             List<QueryOrderAndProductPo>  queryOrderAndProductPoList=tOrderMapper.queryOrderAndProductByCond(map);
             List<UcarOrderQueryApiBoResq> ucarOrdeQueryApiBoResqList=new ArrayList<>();
             for (QueryOrderAndProductPo queryOrderAndProductPo:
                     queryOrderAndProductPoList) {
                 UcarOrderQueryApiBoResq ucarOrdeQueryApiBoResq=new UcarOrderQueryApiBoResq();
                 ucarOrdeQueryApiBoResq.setOrderUuidMapping(ucarOrdeQueryApiBoReq.getOrderUuid());
                 ucarOrdeQueryApiBoResq.setProductUuidMapping(queryOrderAndProductPo.getProductUuid());
                 ucarOrdeQueryApiBoResq.setOrderProductDataUuid(queryOrderAndProductPo.getOrderProductDataUuid());
                 if(StringUtils.isEmpty(queryOrderAndProductPo.getQueryreportOrderId())&&queryOrderAndProductPo.getProductStatus()==1&&queryOrderAndProductPo.getStoreNumber()>0)
                 {
                     if("lemonQueryAccident".equals(queryOrderAndProductPo.getProductType())||"cheXinMengQueryAccident".equals(queryOrderAndProductPo.getProductType())){
                         List<TOrderProductData>  tOrderProductDataList= tOrderProductDataMapper.selectList(new LambdaQueryWrapper<TOrderProductData>().isNotNull(TOrderProductData::getReportDatetime).ge(TOrderProductData::getReportDatetime, LocalDateTime.now().withHour(0).withMinute(0))  // 大于等于当天00:00
                                 .le(TOrderProductData::getReportDatetime, LocalDateTime.now().withHour(23).withMinute(59)).eq(TOrderProductData::getVin,queryOrderAndProductPo.getVin()).eq(TOrderProductData::getProductUuidMapping,queryOrderAndProductPo.getProductUuid()).eq(TOrderProductData::getDeleteFlag,1l).isNotNull(TOrderProductData::getQueryreportUrl));

                           if(StringUtils.isNotNull(tOrderProductDataList)&&tOrderProductDataList.size()>0){
                               TOrderProductData tOrderProductData = tOrderProductDataMapper.selectOne(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderProductDataUuid, queryOrderAndProductPo.getOrderProductDataUuid()).eq(TOrderProductData::getDeleteFlag, 1));
                               tOrderProductData.setQueryreportOrderId(tOrderProductDataList.get(0).getQueryreportOrderId());
                               tOrderProductData.setRemark(tOrderProductDataList.get(0).getRemark());
                               tOrderProductData.setQueryreportUrl(tOrderProductDataList.get(0).getQueryreportUrl());
                               tOrderProductData.setReportDatetime(LocalDateTimeUtil.now());
                               ucarOrdeQueryApiBoResq.setQueryreportOrderId(tOrderProductDataList.get(0).getQueryreportOrderId());
                               ucarOrdeQueryApiBoResq.setQueryreportUrl(tOrderProductDataList.get(0).getQueryreportUrl());
                               tOrderProductDataMapper.updateById(tOrderProductData);
                               //产品库存数减一
                               TProduct tProduct = new TProduct();
                               tProduct.setDeleteFlag(1l);
                               tProduct.setProductUuid(queryOrderAndProductPo.getProductUuid());
                               tProductMapper.tProductStoreNumberMinusone(tProduct);
                               //未读数量加1
                               tCustomerMapper.customerReportUnReadNumberAddone(map);
                               order.setIsReturnPrice(1);
                               tOrderMapper.updateById(order);
                           }else{
                               if("lemonQueryAccident".equals(queryOrderAndProductPo.getProductType())){
                                   LemonApiQueryBoReq  lemonApiQueryBoReq=new LemonApiQueryBoReq();
                                   lemonApiQueryBoReq.setVin(queryOrderAndProductPo.getVin());
                                   ObsImageBoResp obsImageBoRes=  sysFileMainService.obsDownloadImageToBase64String(queryOrderAndProductPo.getUploadFileMainUuid());
                                   lemonApiQueryBoReq.setImgVehicleLicense(obsImageBoRes.getBase64String());
                                   List<SysFileData>  sysFileDataList=sysFileDataMapper.selectList(new LambdaQueryWrapper<SysFileData>().eq(SysFileData::getFileMainUuid,queryOrderAndProductPo.getUploadFileMainUuid()).eq(SysFileData::getDeleteFlag,1));
                                   lemonApiQueryBoReq.setImageType(1);
                                   if(sysFileDataList!=null&&sysFileDataList.size()>0&&"drivingLicense".equals(sysFileDataList.get(0).getFileType())){
                                       lemonApiQueryBoReq.setImageType(1);
                                   }
                                   if(sysFileDataList!=null&&sysFileDataList.size()>0&&"vehicleRegistration".equals(sysFileDataList.get(0).getFileType())){
                                       lemonApiQueryBoReq.setImageType(2);
                                   }
                                   CommonLemonBoResp commonLemonBoResp= uCarQueryApiService.lemonCarApiQuery(lemonApiQueryBoReq);
                                   //需修改成下载报告，上传到OBS系统中。
                                   if (StringUtils.isNull(commonLemonBoResp.getReturnObj())) {
                                       ucarOrdeQueryApiBoResq.setCode(301);
                                       ucarOrdeQueryApiBoResq.setMessage(commonLemonBoResp.getResult() + "|" + commonLemonBoResp.getMessage());
                                       ucarOrdeQueryApiBoResqList.add(ucarOrdeQueryApiBoResq);
                                       break;
                                   } else {
                                       TOrderProductData tOrderProductData = tOrderProductDataMapper.selectOne(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderProductDataUuid, queryOrderAndProductPo.getOrderProductDataUuid()).eq(TOrderProductData::getDeleteFlag, 1));
                                       String queryReportOrderId = ((LemonApiQueryBoResp) commonLemonBoResp.getReturnObj()).getOrderID();
                                       String queryReportUrl = ((LemonApiQueryBoResp) commonLemonBoResp.getReturnObj()).getReportUrl();
                                       tOrderProductData.setQueryreportOrderId(queryReportOrderId);
                                       tOrderProductData.setRemark(queryReportUrl);
                                       String obsImageUrl= reportToImage(queryReportUrl,queryReportOrderId,"Lemon");
                                       if(StringUtils.isNotEmpty(obsImageUrl)){
                                           tOrderProductData.setQueryreportUrl(obsImageUrl);
                                       }
                                       tOrderProductData.setReportDatetime(LocalDateTimeUtil.now());
                                       ucarOrdeQueryApiBoResq.setQueryreportOrderId(queryReportOrderId);
                                       ucarOrdeQueryApiBoResq.setQueryreportUrl(obsImageUrl);
                                       tOrderProductDataMapper.updateById(tOrderProductData);
                                       //产品库存数减一
                                       TProduct tProduct = new TProduct();
                                       tProduct.setDeleteFlag(1l);
                                       tProduct.setProductUuid(queryOrderAndProductPo.getProductUuid());
                                       tProductMapper.tProductStoreNumberMinusone(tProduct);
                                       //未读数量加1
                                       tCustomerMapper.customerReportUnReadNumberAddone(map);
                                       order.setIsReturnPrice(1);
                                       tOrderMapper.updateById(order);
                                   }
                               }else if("cheXinMengQueryAccident".equals(queryOrderAndProductPo.getProductType())) {
                                   CheXinMengApiQueryBoReq cheXinMengApiQueryBoReq = new CheXinMengApiQueryBoReq();
                                   cheXinMengApiQueryBoReq.setVinCode(queryOrderAndProductPo.getVin());
                                   cheXinMengApiQueryBoReq.setServiceUrl("/Service/QueryService.ashx");
                                   ObsImageBoResp obsImageBoRes = sysFileMainService.obsDownloadImageToBase64String(queryOrderAndProductPo.getUploadFileMainUuid());
                                   ObsImageBoResp signObsImageBoRes = sysFileMainService.obsDownloadImageToBase64String(queryOrderAndProductPo.getSignFileMainUuid());
                                   List<SysFileData> sysFileDataList = sysFileDataMapper.selectList(new LambdaQueryWrapper<SysFileData>().eq(SysFileData::getFileMainUuid, queryOrderAndProductPo.getUploadFileMainUuid()).eq(SysFileData::getDeleteFlag, 1));
                                   cheXinMengApiQueryBoReq.setImageType(0);
                                   if(StringUtils.isNotNull(signObsImageBoRes)) {
                                       cheXinMengApiQueryBoReq.setSignImgage(signObsImageBoRes.getBase64String());
                                   }
                                   if (sysFileDataList != null && sysFileDataList.size() > 0 && "drivingLicense".equals(sysFileDataList.get(0).getFileType())) {
                                       cheXinMengApiQueryBoReq.setImageType(0);
                                       cheXinMengApiQueryBoReq.setDrivingLicenceImage(obsImageBoRes.getBase64String());
                                   }
                                   if (sysFileDataList != null && sysFileDataList.size() > 0 && "vehicleRegistration".equals(sysFileDataList.get(0).getFileType())) {
                                       cheXinMengApiQueryBoReq.setImageType(1);
                                       cheXinMengApiQueryBoReq.setRegistrationcertificateImage(obsImageBoRes.getBase64String());
                                   }
                                   CommonCheXinMengBoResp commonCheXinMengBoResp = uCarQueryApiService.cheXinMengApiQuery(cheXinMengApiQueryBoReq);
                                   //需修改成下载报告，上传到OBS系统中。
                                   TOrderProductData tOrderProductData = tOrderProductDataMapper.selectOne(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderProductDataUuid, queryOrderAndProductPo.getOrderProductDataUuid()).eq(TOrderProductData::getDeleteFlag, 1));
                                   if (StringUtils.isNull(commonCheXinMengBoResp.getReturnObj())) {
                                       ucarOrdeQueryApiBoResq.setCode(301);
                                       ucarOrdeQueryApiBoResq.setMessage(commonCheXinMengBoResp.getErrorCode() + "|" + commonCheXinMengBoResp.getMessage());
                                       ucarOrdeQueryApiBoResqList.add(ucarOrdeQueryApiBoResq);
                                       break;
                                   } else{
                                       String queryReportOrderId = ((CheXinMengApiQueryBoResp) commonCheXinMengBoResp.getReturnObj()).getOrderID();
                                       String queryReportUrl = ((CheXinMengApiQueryBoResp) commonCheXinMengBoResp.getReturnObj()).getReportUrl();
                                       tOrderProductData.setQueryreportOrderId(queryReportOrderId);
                                       String obsImageUrl= reportToImage(queryReportUrl,queryReportOrderId,"chexinmeng");
                                       if(StringUtils.isNotEmpty(obsImageUrl)){
                                           tOrderProductData.setQueryreportUrl(obsImageUrl);
                                       }
                                       tOrderProductData.setReportDatetime(LocalDateTimeUtil.now());
                                       ucarOrdeQueryApiBoResq.setQueryreportOrderId(queryReportOrderId);
                                       ucarOrdeQueryApiBoResq.setQueryreportUrl(obsImageUrl);
                                       tOrderProductDataMapper.updateById(tOrderProductData);
                                       //产品库存数减一
                                       TProduct tProduct = new TProduct();
                                       tProduct.setDeleteFlag(1l);
                                       tProduct.setProductUuid(queryOrderAndProductPo.getProductUuid());
                                       tProductMapper.tProductStoreNumberMinusone(tProduct);
                                       //未读数量加1
                                       tCustomerMapper.customerReportUnReadNumberAddone(map);
                                       order.setIsReturnPrice(1);
                                       tOrderMapper.updateById(order);
                                   }
                               }
                           }

                     }

                     //更新代理商的代理费
                     if(StringUtils.isNotEmpty(queryOrderAndProductPo.getParentCustomerUuid())){
                         TCustomer tCustomer=tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>().eq(TCustomer::getCustomerUuid,queryOrderAndProductPo.getParentCustomerUuid()).eq(TCustomer::getDeleteFlag,1l));
                         if(StringUtils.isNotNull(tCustomer.getAgentGrade())&&"first_agent".equals(tCustomer.getAgentGrade())) {
                             UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq = new UpdateAgentTotalAgencyFeeMoReq();
                             updateAgentTotalAgencyFeeMoReq.setAgentCustomerUuid(queryOrderAndProductPo.getParentCustomerUuid());
                             updateAgentTotalAgencyFeeMoReq.setAgencyFee(queryOrderAndProductPo.getAgencyFee());
                             updateAgentTotalAgencyFeeMoReq.setDeleteFlag(1l);
                             tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq);
                         }
                         if(StringUtils.isNotNull(tCustomer.getAgentGrade())&&"second_agent".equals(tCustomer.getAgentGrade())&&queryOrderAndProductPo.getSecondAgencyFeeRatio()>0) {
                             BigDecimal secondAgencyFeeRatio=new BigDecimal(queryOrderAndProductPo.getSecondAgencyFeeRatio())
                                     .divide(new BigDecimal(100));
                             UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq = new UpdateAgentTotalAgencyFeeMoReq();
                             updateAgentTotalAgencyFeeMoReq.setAgentCustomerUuid(queryOrderAndProductPo.getParentCustomerUuid());
                             updateAgentTotalAgencyFeeMoReq.setAgencyFee(queryOrderAndProductPo.getAgencyFee().multiply(secondAgencyFeeRatio)
                                     .setScale(2, RoundingMode.HALF_UP));
                             updateAgentTotalAgencyFeeMoReq.setDeleteFlag(1l);
                             tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq);
                             //更新一级代理费
                             UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq2 = new UpdateAgentTotalAgencyFeeMoReq();
                             updateAgentTotalAgencyFeeMoReq2.setAgentCustomerUuid(tCustomer.getParentCustomerUuid());
                             updateAgentTotalAgencyFeeMoReq2.setAgencyFee(queryOrderAndProductPo.getAgencyFee().multiply(new BigDecimal("1").subtract(secondAgencyFeeRatio).setScale(2, RoundingMode.UP))
                                     .setScale(2, RoundingMode.HALF_UP));
                             updateAgentTotalAgencyFeeMoReq2.setDeleteFlag(1l);
                             tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq2);
                         }
                     }
                     if(StringUtils.isNotEmpty(queryOrderAndProductPo.getCustomerUuid())){
                         TCustomer tCustomer=tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>().eq(TCustomer::getCustomerUuid,queryOrderAndProductPo.getCustomerUuid()).eq(TCustomer::getDeleteFlag,1l));
//                         tCustomer.setGiftMoney(tCustomer.getGiftMoney().add(queryOrderAndProductPo.getTotalReturnPrice()));
                         tCustomerMapper.updateById(tCustomer);
                     }
                     //修改状态
                        UcarOrderUpdateStatusBoReq ucarOrderUpdateStatusBoReq=new UcarOrderUpdateStatusBoReq();
                        ucarOrderUpdateStatusBoReq.setOrderStatus("vaild");
                        ucarOrderUpdateStatusBoReq.setOrderUuid(ucarOrdeQueryApiBoReq.getOrderUuid());
                        this.updateOrderStatus(ucarOrderUpdateStatusBoReq,null);
                 }else{
                     if(StringUtils.isNotEmpty(queryOrderAndProductPo.getQueryreportOrderId())){
                         ucarOrdeQueryApiBoResq.setCode(301);
                         ucarOrdeQueryApiBoResq.setMessage("车辆查询出险服务已使用");
                     }else if(queryOrderAndProductPo.getProductStatus()==-1){
                         ucarOrdeQueryApiBoResq.setCode(301);
                         ucarOrdeQueryApiBoResq.setMessage("该产品已下架");
                     }else if(queryOrderAndProductPo.getStoreNumber()<=0){
                         ucarOrdeQueryApiBoResq.setCode(301);
                         ucarOrdeQueryApiBoResq.setMessage("该产品的库存次数等于零");
                     }
                 }
                 ucarOrdeQueryApiBoResqList.add(ucarOrdeQueryApiBoResq);
             }
             return ucarOrdeQueryApiBoResqList;
    }
    @Override
    @Transactional
    public OrderGetReturnMoneyBoResp getReturnMoney(OrderGetReturnMoneyVoReq orderGetReturnMoneyVoReq){
        OrderGetReturnMoneyBoResp orderGetReturnMoneyBoResp=new OrderGetReturnMoneyBoResp();
        TOrder tOrder=this.baseMapper.selectOne(new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderUuid,orderGetReturnMoneyVoReq.getOrderUuid()).eq(TOrder::getDeleteFlag,1l));
        TCustomer tCustomer= tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>()
                .eq(TCustomer::getSysUserId,SecurityUtils.getLoginUser()
                        .getUserId()).eq(TCustomer::getDeleteFlag,1L));
       if(StringUtils.isNotNull(tOrder)&&StringUtils.isNotNull(tOrder.getReturnPriceDate())){
           if(tOrder.getReturnPriceDate().isBefore(LocalDate.now())){
               orderGetReturnMoneyBoResp.setGetReturnMoneyFlag("exceedReturnPriceDate");
               orderGetReturnMoneyBoResp.setGetReturnMoneyMessage("返现已超过有效期限");
               return orderGetReturnMoneyBoResp;
           }else{
               tCustomer.setReturnMoney(tCustomer.getReturnMoney().add(tOrder.getTotalReturnPrice()));
               tOrder.setIsReturnPrice(2);
               tCustomerMapper.updateById(tCustomer);
               this.baseMapper.updateById(tOrder);
               orderGetReturnMoneyBoResp.setGetReturnMoneyFlag("getReturnMoneySuccess");
               orderGetReturnMoneyBoResp.setGetReturnMoneyMessage("领取返现金额成功！");
               return orderGetReturnMoneyBoResp;
           }
       }
        return orderGetReturnMoneyBoResp;
    }


    @Override
    public OrderMobileQueryListBoResp mobileQueryOrderByCond(OrderMobileQueryListBoReq orderMobileQueryListBoReq) {
        HashMap<String,Object> map=new HashMap<>();
        map.put("deleteFlag",1l);
        map.put("orderStatus",orderMobileQueryListBoReq.getOrderStatus());
        map.put("vin",orderMobileQueryListBoReq.getVin());
        map.put("startDate",orderMobileQueryListBoReq.getStartTime());
        map.put("endDate",orderMobileQueryListBoReq.getEndTime());
        map.put("isHistory",(StringUtils.isNull(orderMobileQueryListBoReq.getIsHistory()) ? new Boolean(false):orderMobileQueryListBoReq.getIsHistory()));
        map.put("customerUuid",tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>()
                .eq(TCustomer::getSysUserId,SecurityUtils.getLoginUser()
                        .getUserId()).eq(TCustomer::getDeleteFlag,1L)).getCustomerUuid());
        map.put("productUuid",orderMobileQueryListBoReq.getProductUuid());
        List<OrderMobileQueryListPo>  orderMobileQueryListPos= this.getBaseMapper().mobileQueryOrderByCond(map);
        if(StringUtils.isNotNull(orderMobileQueryListPos)&&orderMobileQueryListPos.size()>0){

//            OptionalLong maxId = orderMobileQueryListPos.stream()
//                    .mapToLong(OrderMobileQueryListPo::getOrderId)
//                    .max();
            OrderMobileQueryListBoResp orderMobileQueryListBoResp=new OrderMobileQueryListBoResp();
//            orderMobileQueryListBoResp.setLastMaxId(maxId.getAsLong());
            List<OrderMobileQueryListBo> orderMobileQueryListBos=new ArrayList<>();
            orderMobileQueryListPos.forEach(orderMobileQueryListPo -> {
                OrderMobileQueryListBo orderMobileQueryListBo=CommonUtil.objToObj(orderMobileQueryListPo,OrderMobileQueryListBo.class);
                orderMobileQueryListBo.setOrderStatusDict(DictUtils.getDictLabel("order_status",String.valueOf(orderMobileQueryListPo.getOrderStatus())));
                orderMobileQueryListBo.setPayStatusDict(DictUtils.getDictLabel("pay_status",String.valueOf(orderMobileQueryListPo.getPayStatus())));
                orderMobileQueryListBo.setProductTypeDict(DictUtils.getDictLabel("product_type",String.valueOf(orderMobileQueryListPo.getProductType())));
                orderMobileQueryListBo.setOrderTypeDict(DictUtils.getDictLabel("order_type",String.valueOf(orderMobileQueryListPo.getOrderType())));
                orderMobileQueryListBos.add(orderMobileQueryListBo);
            });
            orderMobileQueryListBoResp.setOrderMobileQueryListBos(orderMobileQueryListBos);
            return orderMobileQueryListBoResp;
        }else {
            return null;
        }
    }
    @Override
    public OrderSignBoResq judgeOrderSign(OrderSignQueryBoReq orderSignQueryBoReq){
        OrderSignQueryMoReq orderSignQueryMoReq= CommonUtil.objToObj(orderSignQueryBoReq,OrderSignQueryMoReq.class);
        orderSignQueryMoReq.setDeleteFlag(1l);
        List<OrderSignQueryPo>  orderSignQueryPos=this.tOrderMapper.orderSignQuery(orderSignQueryMoReq);

        if(StringUtils.isNotNull(orderSignQueryPos)&&orderSignQueryPos.size()>0){
            OrderSignBoResq orderSignBoResq=new OrderSignBoResq();
            OrderSignQueryPo orderSignQueryPo=orderSignQueryPos.get(0);
            orderSignBoResq.setSignFileMainUuid(orderSignQueryPo.getSignFileMainUuid());
            orderSignBoResq.setSignFlag(StringUtils.isNotEmpty(orderSignQueryPo.getSignFileMainUuid()) ? new Boolean(true):new Boolean(false));
            return orderSignBoResq;
        }else{
            return null;
        }
    };

    @Override
    public OrderQueryListBoResp queryOrderListByCond(OrderListQueryBoReq orderListQueryBoReq) {
        OrderListQueryMoReq  orderListQueryMoReq=CommonUtil.objToObj(orderListQueryBoReq,OrderListQueryMoReq.class);
        orderListQueryMoReq.setDeleteFlag(1l);
        Page<OrderQueryListPo> page=new Page<>(orderListQueryBoReq.getPageIndex(),orderListQueryBoReq.getPageSize());
         IPage<OrderQueryListPo> orderQueryListPoIPage=tOrderMapper.orderListQueryPage(page,orderListQueryMoReq);
        OrderQueryListBoResp orderQueryListBoResp=new OrderQueryListBoResp();
        if(StringUtils.isNotNull(orderQueryListPoIPage.getRecords())&&orderQueryListPoIPage.getRecords().size()>0){
            orderQueryListBoResp.setTotalCount(new Integer(String.valueOf(orderQueryListPoIPage.getTotal())));
            orderQueryListBoResp.setTotalPage(new Integer(String.valueOf(orderQueryListPoIPage.getPages())));
            List<OrderQueryListBo>   orderQueryListBos=new ArrayList<>();
            orderQueryListPoIPage.getRecords().forEach(orderQueryListPo -> {
                OrderQueryListBo orderQueryListBo=CommonUtil.objToObj(orderQueryListPo,OrderQueryListBo.class);
                orderQueryListBo.setOrderStatusDict(DictUtils.getDictLabel("order_status",String.valueOf(orderQueryListPo.getOrderStatus())));
//                orderQueryListBo.setReturnPriceStatusDict(DictUtils.getDictLabel("return_price_status",orderQueryListPo.getReturnPriceStatus()));
                orderQueryListBo.setPayStatusDict(DictUtils.getDictLabel("pay_status",String.valueOf(orderQueryListPo.getPayStatus())));
                orderQueryListBo.setOrderTypeDict(DictUtils.getDictLabel("order_type",String.valueOf(orderQueryListPo.getOrderType())));
                if(StringUtils.isEmpty(orderQueryListBo.getQueryreportUrl())){
                    List<TOrderProductData> tOrderProductDataList=tOrderProductDataMapper.selectList(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderUuidMapping,orderQueryListBo.getOrderUuid()).eq(TOrderProductData::getDeleteFlag,1l));
                    List<String> queryreportUrls=new ArrayList<>();
                    for(TOrderProductData tOrderProductData:tOrderProductDataList) {
                        List<SysFileData> sysFileDataList= sysFileDataMapper.selectList(new LambdaQueryWrapper<SysFileData>().eq(SysFileData::getFileMainUuid, tOrderProductData.getQueryreportFileMainUuid()));
                        for(SysFileData sysFileData:sysFileDataList) {
                            if(StringUtils.isNotEmpty(sysFileData.getFileUrl())){
                                queryreportUrls.add(sysFileData.getFileUrl());
                            }
                        }
                    }
                    orderQueryListBo.setQueryreportUrls(queryreportUrls);
                }
                orderQueryListBos.add(orderQueryListBo);
            });
            orderQueryListBoResp.setOrderQueryListBos(orderQueryListBos);
            logger.info("订单列表查询BO端返回结果：{}",orderQueryListBoResp);
            return orderQueryListBoResp;
        }else{
            return null;
        }
    }

    @Transactional
    @Override
    public UcarOrderCommitReportBoResq orderCommitReport(UcarOrderCommitReportBoReq ucarOrderCommitReportBoReq,TOrder order) {

        UcarOrderCommitReportBoResq ucarOrderCommitReportBoResq=new UcarOrderCommitReportBoResq();
        try {
            SysFileMain sysFileMain=  sysFileMainService.saveSysFile(ucarOrderCommitReportBoReq.getFiles(), AccessControlList.REST_CANNED_PUBLIC_READ);
            HashMap<String,Object> map=new HashMap<String,Object>();
            map.put("orderUuid",ucarOrderCommitReportBoReq.getOrderUuid());
            map.put("deleteFlag", 1);
            List<QueryOrderAndProductPo>  queryOrderAndProductPoList=tOrderMapper.queryOrderAndProductByCond(map);
            if(StringUtils.isNotNull(queryOrderAndProductPoList)&&queryOrderAndProductPoList.size()>0&&StringUtils.isNotNull(queryOrderAndProductPoList.get(0))){
                QueryOrderAndProductPo queryOrderAndProductPo=queryOrderAndProductPoList.get(0);
            //更新代理商的代理费
            if(StringUtils.isNotEmpty(queryOrderAndProductPo.getParentCustomerUuid())){
                TCustomer tCustomer=tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>().eq(TCustomer::getCustomerUuid,queryOrderAndProductPo.getParentCustomerUuid()).eq(TCustomer::getDeleteFlag,1l));
                if(StringUtils.isNotNull(tCustomer.getAgentGrade())&&"first_agent".equals(tCustomer.getAgentGrade())) {
                    UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq = new UpdateAgentTotalAgencyFeeMoReq();
                    updateAgentTotalAgencyFeeMoReq.setAgentCustomerUuid(queryOrderAndProductPo.getParentCustomerUuid());
                    updateAgentTotalAgencyFeeMoReq.setAgencyFee(queryOrderAndProductPo.getAgencyFee());
                    updateAgentTotalAgencyFeeMoReq.setDeleteFlag(1l);
                    tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq);
                }
                if(StringUtils.isNotNull(tCustomer.getAgentGrade())&&"second_agent".equals(tCustomer.getAgentGrade())&&queryOrderAndProductPo.getSecondAgencyFeeRatio()>0) {
                    BigDecimal secondAgencyFeeRatio=new BigDecimal(queryOrderAndProductPo.getSecondAgencyFeeRatio())
                            .divide(new BigDecimal(100));
                    UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq = new UpdateAgentTotalAgencyFeeMoReq();
                    updateAgentTotalAgencyFeeMoReq.setAgentCustomerUuid(queryOrderAndProductPo.getParentCustomerUuid());
                    updateAgentTotalAgencyFeeMoReq.setAgencyFee(queryOrderAndProductPo.getAgencyFee().multiply(secondAgencyFeeRatio)
                            .setScale(2, RoundingMode.HALF_UP));
                    updateAgentTotalAgencyFeeMoReq.setDeleteFlag(1l);
                    tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq);
                    //更新一级代理费
                    UpdateAgentTotalAgencyFeeMoReq updateAgentTotalAgencyFeeMoReq2 = new UpdateAgentTotalAgencyFeeMoReq();
                    updateAgentTotalAgencyFeeMoReq2.setAgentCustomerUuid(tCustomer.getParentCustomerUuid());
                    updateAgentTotalAgencyFeeMoReq2.setAgencyFee(queryOrderAndProductPo.getAgencyFee().multiply(new BigDecimal("1").subtract(secondAgencyFeeRatio).setScale(2, RoundingMode.UP))
                            .setScale(2, RoundingMode.HALF_UP));
                    updateAgentTotalAgencyFeeMoReq2.setDeleteFlag(1l);
                    tCustomerMapper.updateAgentTotalAgencyFee(updateAgentTotalAgencyFeeMoReq2);
                }
            }
                 TCustomer tCustomer=tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>().eq(TCustomer::getCustomerUuid,queryOrderAndProductPo.getCustomerUuid()).eq(TCustomer::getDeleteFlag,1l));
//                tCustomer.setGiftMoney(tCustomer.getGiftMoney().add(queryOrderAndCustomerPos.get(0).getTotalReturnPrice()));
                tCustomerMapper.updateById(tCustomer);
            }
            //修改状态
            UcarOrderUpdateStatusBoReq ucarOrderUpdateStatusBoReq=new UcarOrderUpdateStatusBoReq();
            ucarOrderUpdateStatusBoReq.setOrderStatus("vaild");
            ucarOrderUpdateStatusBoReq.setOrderUuid(ucarOrderCommitReportBoReq.getOrderUuid());
            this.updateOrderStatus(ucarOrderUpdateStatusBoReq,null);
            TOrderProductData tOrderProductData=tOrderProductDataMapper.selectOne(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderProductDataUuid,ucarOrderCommitReportBoReq.getOrderProductDataUuid()).eq(TOrderProductData::getDeleteFlag,1l));
            if(StringUtils.isNotNull(tOrderProductData)){
                tOrderProductData.setQueryreportFileMainUuid(sysFileMain.getFileMainUuid());
                if(StringUtils.isNotNull(sysFileMain.getFileUrls())&&sysFileMain.getFileUrls().size()==1)
                {tOrderProductData.setQueryreportUrl(sysFileMain.getFileUrls().get(0));}
                tOrderProductData.setReportDatetime(LocalDateTimeUtil.now());
                ucarOrderCommitReportBoResq.setProductUuidMapping(tOrderProductData.getProductUuidMapping());
                tOrderProductDataMapper.updateById(tOrderProductData);
            }
            ucarOrderCommitReportBoResq.setOrderProductDataUuid(ucarOrderCommitReportBoReq.getOrderProductDataUuid());
            ucarOrderCommitReportBoResq.setOrderUuidMapping(ucarOrderCommitReportBoReq.getOrderUuid());
            ucarOrderCommitReportBoResq.setQueryreportUrls(sysFileMain.getFileUrls());
            //产品库存数减一
            TProduct tProduct=new TProduct();
            tProduct.setDeleteFlag(1l);
            tProduct.setProductUuid(tOrderProductData.getProductUuidMapping());
            tProductMapper.tProductStoreNumberMinusone(tProduct);
            //未读数量加一
            tCustomerMapper.customerReportUnReadNumberAddone(map);
            order.setIsReturnPrice(1);
            tOrderMapper.updateById(order);
            return ucarOrderCommitReportBoResq;
        } catch (IOException e) {
            ucarOrderCommitReportBoResq.setCode(ResultEnum.FILEERROR.getCode());
            ucarOrderCommitReportBoResq.setMessage(ResultEnum.FILEERROR.getMsg());
        }
        return ucarOrderCommitReportBoResq;
    }

    @Autowired
    private RedisCache redisCache;

    @Override
    public   List<TBrandPrice> getBrandPriceCache(String productType)
    {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.BRAND_PRICE_KEY+productType);
        if (StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(TBrandPrice.class);
        }
        return null;
    }
    @Transactional
    @Override
    public UcarOrderBoResp initOrder(UcarOrderBoReq ucarOrderBoReq) throws IOException {
        BigDecimal totalPrice=new BigDecimal(0.00);
        BigDecimal totalRealPrice=new BigDecimal(0.00);
        BigDecimal totalPurchasingPrice=new BigDecimal(0.00);
        BigDecimal totalReturnPrice=new BigDecimal(0.00);
        BigDecimal totalAgencyFee=new BigDecimal(0.00);
        List<TOrderProductData> tOrderProductDataList=new ArrayList<>();
        List<Long> returnPriceDays=new ArrayList<>();
        String orderType=null;
        if(ucarOrderBoReq.getProductUuidList().size()>1){
            orderType="blanketOrder";
        }
        //计算订单的总价格和总进价
        for (String productUuid:ucarOrderBoReq.getProductUuidList()
        ) {
            TProduct tProduct=tProductMapper.selectOne(new LambdaQueryWrapper<TProduct>().eq(TProduct::getProductUuid,productUuid)
                    .eq(TProduct::getDeleteFlag,1));
            if (StringUtils.isNotNull(tProduct)){
                if(StringUtils.isNotNull(tProduct.getProductAgencyFee())) {
                    totalAgencyFee = totalAgencyFee.add(tProduct.getProductAgencyFee());
                }
                if ("lemonQueryAccident".equals(tProduct.getProductType())||"cheXinMengQueryAccident".equals(tProduct.getProductType())||"batteryReport".equals(tProduct.getProductType())||"cloudCheckTable".equals(tProduct.getProductType())){
                        totalRealPrice=totalRealPrice.add(tProduct.getProductRealPrice());
                        totalPrice=totalPrice.add(tProduct.getProductPrice());
                        totalPurchasingPrice=totalPurchasingPrice.add(tProduct.getProductPurchasingPrice());
                        totalReturnPrice=totalReturnPrice.add(tProduct.getProductReturnPrice());
                }else{
                    List<TBrandPrice> tBrandPriceList=getBrandPriceCache(tProduct.getProductType());
                    if(tBrandPriceList!=null&&tBrandPriceList.size()>0){
                        for (TBrandPrice tBrandPrice:tBrandPriceList ){
                            if(UcarConstants.specialBrand.contains(ucarOrderBoReq.getBrandModel())) {
                                if(ucarOrderBoReq.getBrandModel().equals(tBrandPrice.getVehicleBrand())){
                                    totalRealPrice=totalRealPrice.add(tBrandPrice.getRealPrice());
                                    totalPrice=totalPrice.add(tBrandPrice.getPrice());
                                    totalPurchasingPrice=totalPurchasingPrice.add(tBrandPrice.getPurchasingPrice());
                                    totalReturnPrice=totalReturnPrice.add(tBrandPrice.getReturnPrice());
                                    break;
                                }
                            }else{
                                if(ucarOrderBoReq.getBrandModel().contains(tBrandPrice.getVehicleBrand())){
                                    totalRealPrice=totalRealPrice.add(tBrandPrice.getRealPrice());
                                    totalPrice=totalPrice.add(tBrandPrice.getPrice());
                                    totalPurchasingPrice=totalPurchasingPrice.add(tBrandPrice.getPurchasingPrice());
                                    totalReturnPrice=totalReturnPrice.add(tBrandPrice.getReturnPrice());
                                    break;
                                }
                            }
                        }
                    }
                }

                if(StringUtils.isNull(orderType)){
                    switch (tProduct.getProductType()){
                        case "uCarQueryMainten":
                            orderType="uCarQueryMaintenOrder";
                            break;
                        case "uCarPreciseQuery":
                            orderType="uCarPreciseQueryOrder";
                            break;
                        case "batteryReport":
                            orderType="batteryReportOrder";
                            break;
                        case "cloudCheckTable":
                            orderType="cloudCheckTableOrder";
                            break;
                        default:
                            orderType="commonOrder";
                            break;
                    }
                }
            }
            TOrderProductData tOrderProductData=new TOrderProductData();
            tOrderProductData.setOrderProductDataUuid(CommonUtil.createUuid());
            if(StringUtils.isNull(tProduct.getProductReturnPrice())||tProduct.getProductReturnPrice().compareTo(new BigDecimal(0.00))==0){
                tOrderProductData.setReturnPriceStatus("invalid");
            }else {
                tOrderProductData.setReturnPriceStatus("waitVaild");
                tOrderProductData.setReturnPrice(tProduct.getProductReturnPrice());
                if (StringUtils.isNotNull(tProduct.getReturnPriceDays()) && tProduct.getReturnPriceDays() != 0) {
                    tOrderProductData.setReturnPriceDate(LocalDate.now().plusDays(tProduct.getReturnPriceDays()));
                }
            }
                tOrderProductData.setUploadFileMainUuid(ucarOrderBoReq.getFileUuid());
                tOrderProductData.setVin(ucarOrderBoReq.getVinNo());
                tOrderProductData.setVehicleBrand(ucarOrderBoReq.getBrandModel());
                tOrderProductData.setDeleteFlag(1l);
                tOrderProductData.setCreatedBy(SecurityUtils.getUsername());
                tOrderProductData.setProductUuidMapping(productUuid);
                tOrderProductDataList.add(tOrderProductData);
                if(StringUtils.isNotNull(tProduct.getReturnPriceDays())&&tProduct.getReturnPriceDays()>0){
                    returnPriceDays.add(tProduct.getReturnPriceDays());
                }
        }
//        if(totalRealPrice.compareTo(new BigDecimal(0.00))==0){
//            return new UcarOrderBoResp();
//        }
          TOrder tOrder=new TOrder();
          tOrder.setTotalRealPrice(totalRealPrice);
          tOrder.setOrderType(orderType);
          tOrder.setTotalPrice(totalPrice);
          tOrder.setTotalPurchasingPrice(totalPurchasingPrice);
          tOrder.setTotalReturnPrice(totalReturnPrice);
          tOrder.setOrderStatus("init");
          tOrder.setIsReturnPrice(0);
          tOrder.setPayStatus("waitPay");
          tOrder.setOrderUuid(CommonUtil.createUuid());
          tOrder.setDeleteFlag(1l);
          tOrder.setCreatedBy(SecurityUtils.getUsername());
          tOrder.setOrderCode(NanoTimestampUtil.getNanoTimestamp());
          if(totalReturnPrice.compareTo(new BigDecimal(0.00)) > 0) {
              if (returnPriceDays.size() > 0 ) {
                  Long minReturnPriceDay = Collections.min(returnPriceDays);
                  tOrder.setReturnPriceDate(LocalDate.now().plusDays(minReturnPriceDay));
              }
          }
          //订单失效时间往后延期30个小时
           tOrder.setOrderFailureDatetime(LocalDateTimeUtil.offset(LocalDateTimeUtil.now(),30, ChronoUnit.HOURS));
           TCustomer tCustomer= tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>()
                        .eq(TCustomer::getSysUserId,SecurityUtils.getLoginUser()
                                .getUserId()).eq(TCustomer::getDeleteFlag,1L));
           if(StringUtils.isNotNull(tCustomer)){
              tOrder.setCustomerUuidMapping(
                   tCustomer.getCustomerUuid()
                   );
               if(StringUtils.isNotEmpty(tCustomer.getParentCustomerUuid())){
                   tOrder.setAgencyFee(totalAgencyFee);
               }
           }
         tOrderMapper.insert(tOrder);
        for (TOrderProductData tOrderProductData:tOrderProductDataList
             ) {
            tOrderProductData.setOrderUuidMapping(tOrder.getOrderUuid());
            tOrderProductDataMapper.insert(tOrderProductData);
        }
          UcarOrderBoResp ucarOrderBoResp=new UcarOrderBoResp();
          ucarOrderBoResp.setOrderUuid(tOrder.getOrderUuid());
          ucarOrderBoResp.setOrderCode(tOrder.getOrderCode());
          ucarOrderBoResp.setTotalRealPrice(totalRealPrice);
          return ucarOrderBoResp;
    }

    @Override
    public int updateOrderStatus(UcarOrderUpdateStatusBoReq ucarOrderUpdateStatusBoReq, TCustomer tCustomer) {
        Wrapper<TOrder>  wrapper=null;
        if(StringUtils.isNotEmpty(ucarOrderUpdateStatusBoReq.getOrderUuid())) {
            wrapper = new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderUuid, ucarOrderUpdateStatusBoReq.getOrderUuid()).eq(TOrder::getDeleteFlag, 1l);
        }else{
            wrapper = new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderCode, ucarOrderUpdateStatusBoReq.getOrderCode()).eq(TOrder::getDeleteFlag, 1l);
        }
        TOrder tOrder=  tOrderMapper.selectOne(wrapper);
        if(StringUtils.isNotEmpty(ucarOrderUpdateStatusBoReq.getOrderStatus())){
            tOrder.setOrderStatus(ucarOrderUpdateStatusBoReq.getOrderStatus());
        }
        if(StringUtils.isNotEmpty(ucarOrderUpdateStatusBoReq.getPayStatus())){
            tOrder.setPayStatus(ucarOrderUpdateStatusBoReq.getPayStatus());
        }
        if(StringUtils.isNotNull(ucarOrderUpdateStatusBoReq.getPayDatetime())){
            tOrder.setPayDatetime(ucarOrderUpdateStatusBoReq.getPayDatetime());
        }
        if(StringUtils.isNotNull(ucarOrderUpdateStatusBoReq.getTransactionId())) {
            tOrder.setTransactionId(ucarOrderUpdateStatusBoReq.getTransactionId());
        }
        if(StringUtils.isNotNull(ucarOrderUpdateStatusBoReq.getChargeDatetime())) {
            tOrder.setChargeDatetime(ucarOrderUpdateStatusBoReq.getChargeDatetime());
        }
        if(StringUtils.isNotNull(ucarOrderUpdateStatusBoReq.getIsReturnPrice())) {
            tOrder.setIsReturnPrice(ucarOrderUpdateStatusBoReq.getIsReturnPrice());
        }
        if(StringUtils.isNotNull(tCustomer)){
            BigDecimal  zeroBigDecimal= new BigDecimal(0.00);
            if(tOrder.getIsReturnPrice()==2&&tOrder.getTotalReturnPrice().compareTo(zeroBigDecimal)>0) {
                BigDecimal  backReturnMoney=tOrder.getTotalReturnPrice();
                if (tCustomer.getReturnMoney().compareTo(tOrder.getTotalReturnPrice()) >= 0) {
                    tCustomer.setReturnMoney(tCustomer.getReturnMoney().subtract(tOrder.getTotalReturnPrice()));
                }else{
                    tCustomer.setReturnMoney(zeroBigDecimal);
                    backReturnMoney=tCustomer.getReturnMoney();
                }
                TConsumeData tConsumeData=new TConsumeData();
                tConsumeData.setCustomerUuid(tCustomer.getCustomerUuid());
                tConsumeData.setDeleteFlag(1l);
                tConsumeData.setConsumeMoney(backReturnMoney);
                tConsumeData.setBalanceMoney(tCustomer.getGiftMoney().add(tCustomer.getBalanceNumber()).add(tCustomer.getReturnMoney()).add(tCustomer.getTotalAgencyFee()));
                tConsumeData.setConsumeType("backReturnMoney");
                tConsumeDataMapper.insert(tConsumeData);
            }
            tCustomerMapper.updateById(tCustomer);
        }
        return tOrderMapper.update(tOrder,wrapper);
    }

    @Override
    public int updateOrderTransactionId(UcarOrderUpdateTransactionIdBoReq ucarOrderUpdateTransactionIdBoReq) {
        Wrapper<TOrder>  wrapper=new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderCode, ucarOrderUpdateTransactionIdBoReq.getOrderCode()).eq(TOrder::getDeleteFlag, 1l);;
        TOrder tOrder=  tOrderMapper.selectOne(wrapper);
        tOrder.setTransactionId(ucarOrderUpdateTransactionIdBoReq.getTransactionId());
        return tOrderMapper.update(tOrder,wrapper);
    }


    /**
     * 查询订单主
     * 
     * @param id 订单主主键
     * @return 订单主
     */
    @Override
    public TOrder selectTOrderById(Long id)
    {
        return tOrderMapper.selectTOrderById(id);
    }

    /**
     * 查询订单主列表
     * 
     * @param tOrder 订单主
     * @return 订单主
     */
    @Override
    public List<TOrder> selectTOrderList(TOrder tOrder)
    {
        return tOrderMapper.selectTOrderList(tOrder);
    }

    /**
     * 新增订单主
     * 
     * @param tOrder 订单主
     * @return 结果
     */
    @Override
    public int insertTOrder(TOrder tOrder)
    {
        return tOrderMapper.insertTOrder(tOrder);
    }

    /**
     * 修改订单主
     * 
     * @param tOrder 订单主
     * @return 结果
     */
    @Override
    public int updateTOrder(TOrder tOrder)
    {
        return tOrderMapper.updateTOrder(tOrder);
    }

    /**
     * 批量删除订单主
     * 
     * @param ids 需要删除的订单主主键
     * @return 结果
     */
    @Override
    public int deleteTOrderByIds(Long[] ids)
    {
        return tOrderMapper.deleteTOrderByIds(ids);
    }

    /**
     * 删除订单主信息
     * 
     * @param id 订单主主键
     * @return 结果
     */
    @Override
    public int deleteTOrderById(Long id)
    {
        return tOrderMapper.deleteTOrderById(id);
    }

    @Override
    public OrderDetailQueryBoResp orderDetailQuery(OrderDetailQueryBoReq orderDetailQueryBoReq) {
        OrderDetailQueryMoReq orderDetailQueryMoReq=CommonUtil.objToObj(orderDetailQueryBoReq, OrderDetailQueryMoReq.class)  ;
        orderDetailQueryMoReq.setDeleteFlag(1l);
        List<OrderDetailQueryPo> orderDetailQueryPos=tOrderMapper.orderDetailQuery(orderDetailQueryMoReq);
        if(StringUtils.isNotNull(orderDetailQueryPos)&&orderDetailQueryPos.size()>0){
            OrderDetailQueryPo orderDetailQueryPo=orderDetailQueryPos.get(0);
            OrderDetailQueryBoResp orderDetailQueryBoResp=CommonUtil.objToObj(orderDetailQueryPo,OrderDetailQueryBoResp.class);
            orderDetailQueryBoResp.setOrderStatusDict(DictUtils.getDictLabel("order_status",String.valueOf(orderDetailQueryPo.getOrderStatus())));
//            orderDetailQueryBoResp.setReturnPriceStatusDict(DictUtils.getDictLabel("return_price_status",orderDetailQueryPo.getReturnPriceStatus()));
            orderDetailQueryBoResp.setPayStatusDict(DictUtils.getDictLabel("pay_status",orderDetailQueryPo.getPayStatus()));
            orderDetailQueryBoResp.setOrderTypeDict(DictUtils.getDictLabel("order_type",orderDetailQueryPo.getOrderType()));

            if(StringUtils.isEmpty(orderDetailQueryBoResp.getQueryreportUrl())){
                List<TOrderProductData> tOrderProductDataList=tOrderProductDataMapper.selectList(new LambdaQueryWrapper<TOrderProductData>().eq(TOrderProductData::getOrderUuidMapping,orderDetailQueryPo.getOrderUuid()).eq(TOrderProductData::getDeleteFlag,1l));
                List<String> queryreportUrls=new ArrayList<>();
                for(TOrderProductData tOrderProductData:tOrderProductDataList) {
                   List<SysFileData> sysFileDataList= sysFileDataMapper.selectList(new LambdaQueryWrapper<SysFileData>().eq(SysFileData::getFileMainUuid, tOrderProductData.getQueryreportFileMainUuid()));
                    for(SysFileData sysFileData:sysFileDataList) {
                           if(StringUtils.isNotEmpty(sysFileData.getFileUrl())){
                               queryreportUrls.add(sysFileData.getFileUrl());
                           }
                    }
                }
                orderDetailQueryBoResp.setQueryreportUrls(queryreportUrls);
            }
            return orderDetailQueryBoResp;
        }else{
            return null;
        }
    }

    @Override
    public String uploadOrderSign(UploadOrderSignBoReq uploadOrderSignBoReq) throws IOException {
        TOrder tOrder=this.tOrderMapper.selectOne(new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderCode,uploadOrderSignBoReq.getOrderCode()).eq(TOrder::getDeleteFlag,1l));
        TCustomer tCustomer=this.tCustomerMapper.selectOne(new LambdaQueryWrapper<TCustomer>().eq(TCustomer::getCustomerPhone,SecurityUtils.getUsername()).eq(TCustomer::getDeleteFlag,1l));
        if(StringUtils.isNotNull(tCustomer)) {
            tCustomer.setRealName(uploadOrderSignBoReq.getRealName());
            tCustomer.setCardNo(uploadOrderSignBoReq.getCarNo());
            this.tCustomerMapper.updateById(tCustomer);
        }
        String signFileMainUuid = sysFileMainService.saveSysFile(uploadOrderSignBoReq.getFile());
        if(StringUtils.isNotNull(tOrder)&&StringUtils.isNotEmpty(signFileMainUuid)) {
            tOrder.setSignFileMainUuid(signFileMainUuid);
            this.tOrderMapper.updateById(tOrder);
            return signFileMainUuid;
        }else{
            return null;
        }
    }

    @Override
    public TOrder selectOrderByOrderUuid(String orderUuid) {
        return this.tOrderMapper.selectOne(new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderUuid,orderUuid).eq(TOrder::getDeleteFlag,1l));
    }

    @Override
    public OrderDetailQueryBoResp orderDetailQuery2(OrderDetailQueryBoReq orderDetailQueryBoReq) {
        OrderDetailQueryMoReq orderDetailQueryMoReq=CommonUtil.objToObj(orderDetailQueryBoReq, OrderDetailQueryMoReq.class)  ;
        orderDetailQueryMoReq.setDeleteFlag(1l);
        List<OrderDetailQueryPo> orderDetailQueryPos=tOrderMapper.orderDetailQuery2(orderDetailQueryMoReq);
        if(StringUtils.isNotNull(orderDetailQueryPos)&&orderDetailQueryPos.size()>0){
            OrderDetailQueryPo orderDetailQueryPo=orderDetailQueryPos.get(0);
            OrderDetailQueryBoResp orderDetailQueryBoResp=CommonUtil.objToObj(orderDetailQueryPo,OrderDetailQueryBoResp.class);
            return orderDetailQueryBoResp;
        }else{
            return null;
        }
    }


    @Override
    public int deleteTOrderById(String orderUuid, Long id) {
        TOrder  tOrder=null;
        if(StringUtils.isNotEmpty(orderUuid)) {
            tOrder = this.selectOrderByOrderUuid(orderUuid);
            tOrder.setDeleteFlag(-1l);
            tOrder.setUpdatedBy(SecurityUtils.getUsername());
            return this.tOrderMapper.update(tOrder,new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderUuid, orderUuid));
        }else{
            tOrder = this.getById(id);
            tOrder.setDeleteFlag(-1l);
            tOrder.setUpdatedBy(SecurityUtils.getUsername());
            return this.tOrderMapper.update(tOrder,new LambdaQueryWrapper<TOrder>().eq(TOrder::getId, id));
        }
    }


    @Override
    public int batchDelete(String[] orderUuids, Long[] ids) {
        if(StringUtils.isNotNull(orderUuids)&&orderUuids.length>0) {
            return this.tOrderMapper.deleteTOrderByUuids(-1l, orderUuids);
        }else{
            return this.tOrderMapper.deleteTOrderByids(-1l, ids);
        }
    }
}
